from flask import Flask, request, jsonify, render_template
from openai import OpenAI

app = Flask(__name__)

def call_deepseek_v3_api(user_message):
    try:
        client = OpenAI(api_key="sk-5f87292120454a4b9ab0372ed9aa1a18", base_url="https://api.deepseek.com")
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "You are a helpful assistant"},
                {"role": "user", "content": user_message},
            ],
            stream=False
        )
        return response.choices[0].message.content
    except Exception as e:
        print(f"API call failed: {e}")
        return "Sorry, I couldn't process your request."

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    user_message = data.get('message', '')
    print(f"Received message: {user_message}")  # 打印用户输入

    # 调用API生成回复
    ai_response = call_deepseek_v3_api(user_message)
    print(f"AI response: {ai_response}")  # 打印AI回复

    # 返回AI回复
    return jsonify({'response': ai_response})

if __name__ == '__main__':
#    app.run(debug=True)
    app.run(host='127.0.0.1', port=5000)